<template>
  <!-- 添加或修改盘点计划对话框 -->
  <!-- <el-dialog :title="title" v-model="open" width="1400px" append-to-body> -->
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="90px" :inline="true" :disabled="disabled">
      <div class="top-line">
        <div style="padding-left: 30px">
          <!-- <el-form :model="form">
            <el-button type="primary" @click="add">新增</el-button>
            <el-button type="success" @click="edit">修改</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="cancel">取 消</el-button>
          </el-form> -->
        </div>
        <div>
          <el-form-item label="录单日期:" prop="payOrderDate">
            <el-date-picker
              v-model="form.payOrderDate"
              style="width: 150px"
              value-format="YYYY-MM-DD hh:mm:ss"
              type="date"
              placeholder="选择合同日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="续费单号:" prop="payOrderCode">
            <el-input
              v-model="form.payOrderCode"
              placeholder="自动生成"
              style="width: 200px; padding-right: 10px"
              :disabled="disabledCode"
            ></el-input>
            <el-button @click="addInit" :disabled="disabledCode">
              <el-icon :size="20">
                <RefreshRight />
              </el-icon>
            </el-button>
          </el-form-item>
        </div>
      </div>
      <el-form-item label="客户:" prop="supplierId">
        <el-select
          v-model="form.supplierId"
          filterable
          clearable
          remote
          reserve-keyword
          placeholder="请选择客户"
          @change="customerChange"
          :remote-method="(query) => remoteMethod(query, 'supplier', 'supplierName')"
          :loading="loading"
        >
          <el-option v-for="item in supplierOptions" :key="item.id" :label="item.supplierName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="联系人:" prop="contacts">
        <el-select v-model="form.contacts" filterable clearable remote reserve-keyword placeh :loading="loading">
          <el-option v-for="item in contactsOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户经理:" prop="operationManagerName">
        <el-input v-model="form.operationManagerName" filterable clearable remote disabled :loading="loading"> </el-input>
      </el-form-item>
      <el-form-item label="经手人" prop="userId">
        <el-select v-model="form.userId" filterable clearable remote reserve-keyword placeholder="请选择经手人" :loading="loading">
          <el-option v-for="item in userList" :key="item.value" :label="item.realityName" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="22">
          <el-form-item label="备注:" prop="remark" style="width: 100%">
            <el-input style="width: 100%" :rows="4" v-model="form.remark"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item class="pl-4">
            <el-image :src="img" fit="scale-down" style="width: 60px; height: 60px" v-if="disabled">已审核</el-image>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-card class="box-card" shadow="always">
      <template #header v-if="disabled === false">
        <el-button type="primary" @click="handleAdd">添加商品</el-button>
        <el-button v-if="multiple" type="danger" @click="handleBatchDelete">删除</el-button>
      </template>
      <el-table :summary-method="getSummaries" show-summary border scrollbar-always-on :data="dataSource" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="80" align="center" :selectable="selectHandle" />
        <el-table-column label="#" type="index" width="55" align="center"> </el-table-column>
        <!-- <el-table-column label="商品分类" align="center" prop="classifyName" width="150">
          <template #default="scope">
            {{ scope.row.classifyName }}
          </template>
        </el-table-column>
 
        <el-table-column label="商品来源" align="center" prop="goodsType" width="150">
          <template #default="scope">
            {{ selectDictLabel(goods_source, scope.row.goodsType) }}
          </template>
        </el-table-column> -->
        <el-table-column label="商品名称" align="left" prop="goodsId" min-width="200">
          <template #default="scope">
            {{ scope.row.goodsName }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="商品规格" align="center" prop="goodsSpec" width="100" /> -->
        <el-table-column label="计价方式" align="center" prop="payTypeDictValue" width="100">
          <template #default="scope">
            {{ selectDictLabel(goods_price_type, scope.row.payTypeDictValue) }}
          </template>
        </el-table-column>
        <el-table-column label="商品数量" align="center" prop="goodsNumber" width="100">
          <template #default="scope">
            <el-input
              v-model="scope.row.goodsNumber"
              @change="quantityChange(scope.row, scope.$index)"
              :disabled="disabled"
              onkeyup="value=(value.replace(/\D/g,'')==''?'':parseInt(value))"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="goodsPrice" width="100">
          <template #default="scope">
            <el-input v-model="scope.row.goodsPrice" @change="quantityChange(scope.row, scope.$index)" :disabled="disabled"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="goodsAmount" width="100" />
        <el-table-column label="续费金额" align="center" prop="payAmount" width="100">
          <template #default="scope">
            <el-input v-model="scope.row.payAmount" :disabled="disabled"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="开始日期" align="center" prop="beginDate" min-width="180">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.beginDate"
              type="date"
              style="width: 100%"
              :picker-ptions="pickerOptionsStart"
              value-format="YYYY-MM-DD hh:mm:ss"
              @change="handlePeriodicNumChange(scope.row)"
              :disabled="disabled"
            ></el-date-picker>
          </template>
        </el-table-column>

        <el-table-column label="周期" align="center" prop="periodicNum" width="120">
          <template #default="scope">
            <el-input v-model.number="scope.row.periodicNum" @change="handlePeriodicNumChange(scope.row)" :disabled="disabled"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="到期日期" align="center" prop="endDate" min-width="180">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.endDate"
              type="date"
              style="width: 100%"
              :picker-ptions="pickerOptionsEnd"
              value-format="YYYY-MM-DD hh:mm:ss"
              @change="handleEndDateChange(scope.row)"
              :disabled="disabled"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="单据备注" align="center" prop="comment" min-width="200">
          <template #default="scope">
            <el-input v-model="scope.row.comment" placeholder="请输入备注" :disabled="disabled"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card header="历史单" class="box-card" shadow="always">
      <el-table
        :summary-method="getSummaries"
        show-summary
        border
        scrollbar-always-on
        :data="historyDataSource"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="80" align="center" :selectable="selectHandle" /> -->
        <el-table-column label="#" type="index" width="55" align="center"> </el-table-column>
        <el-table-column label="商品名称" align="left" prop="goodsName" min-width="200" />
        <!-- <el-table-column label="商品规格" align="center" prop="goodsSpec" width="100" /> -->
        <el-table-column label="计价方式" align="center" prop="payTypeDictValue" width="100">
          <template #default="scope">
            {{ selectDictLabel(goods_price_type, scope.row.payTypeDictValue) }}
          </template>
        </el-table-column>
        <el-table-column label="商品数量" align="center" prop="goodsNumber" width="100" />
        <el-table-column label="单价" align="center" prop="goodsPrice" width="100" />
        <el-table-column label="金额" align="center" prop="goodsAmount" width="100" />
        <el-table-column label="续费金额" align="center" prop="payAmount" width="100" />
        <el-table-column label="开始日期" align="center" prop="beginDate" min-width="200" />
        <el-table-column label="周期" align="center" prop="periodicNum" width="120" />
        <el-table-column label="到期日期" align="center" prop="endDate" min-width="200" />
        <el-table-column label="单据备注" align="center" prop="remark" min-width="200" />
      </el-table>
      <div style="text-align: center; padding-top: 20px" v-if="!disabled">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
      <div style="text-align: center; padding-top: 20px" v-if="disabled">
        <el-button @click="cancel">返回</el-button>
      </div>
    </el-card>
    <selectMaterialForm ref="selectMaterialForm" @ok="selectOk"></selectMaterialForm>
  </div>
</template>
 
<script>
import selectMaterialForm from '@/views/goods/quote/modules/selectMaterialForm.vue';
import modelMixin from '@/mixins/modelMixin';
import { listUser } from '@/api/system/user';
import payOrder, { getPayOrderCode } from '@/api/goods/payOrder';
import { listPayOrderHistoryDetail } from '@/api/goods/payOrderDetail';
import { getSupplier } from '@/api/goods/supplier';
import { formatDate } from '@/utils/index';
import { getPayOrder } from '@/api/goods/payOrder';
import { useUserStore } from '@/store/modules/user';
import yishenhe from '@/assets/images/yishenhe.png';

const userStore = useUserStore();
import moment from 'moment';
export default {
  name: 'addForm',
  components: {
    selectMaterialForm
  },
  mixins: [modelMixin],
  data() {
    return {
      open: false,
      title: '添加续费单',
      funcObj: payOrder,
      multiple: false,
      selectedRows: [],
      form: {
        quotationStatus: 0
      },
      supplierOptions: [], //客户
      contactsOptions: [], //联系人
      userList: [], //经手人
      rules: {
        supplierId: [
          {
            required: true,
            message: '请选择客户',
            trigger: 'blur'
          }
        ],
        userId: [
          {
            required: true,
            message: '请选择经手人',
            trigger: 'blur'
          }
        ],
        payOrderCode: [
          {
            required: true,
            message: '请输入单据编号'
          }
        ],
        payOrderDate: [
          {
            required: true,
            message: '请选择录单日期'
          }
        ]
      },
      active: 1,
      baseInput: 200,
      data: [],
      dateRange: [],
      dataSource: [],
      historyDataSource: [],
      loading: false,
      goods_price_type: [],
      disabled: false,
      img: yishenhe,
      enterType: '0', //判断页面进入方式
      disabledCode: false
    };
  },
  mounted() {
    if (this.$route.query.type == 'edit') {
      this.edit(JSON.parse(this.$route.query.dataList));
    } else if (this.$route.query.type == 'view') {
      this.view(JSON.parse(this.$route.query.dataList));
    } else {
      this.add();
    }

    if (this.$route.query.id) {
      console.log('this.$route.query :>> ', this.$route.query);
      this.view(this.$route.query);
    }
    this.enterType = this.$route.query.enterType;
  },
  methods: {
    add() {
      this.open = true;
      this.disabled = false;
      this.disabledCode = false;
      this.title = '添加续费单';
      this.form = {
        payOrderDate: moment().format('YYYY-MM-DD HH:mm:ss'),
        userId: userStore.userId
      };
      this.dataSource = [];
      this.addInit();
      this.listSysUser();
      this.getSupplierAllList(1);
      this.getDicts('goods_price_type');
    },
    edit(row) {
      this.open = true;
      this.disabled = false;
      this.title = '编辑续费单';
      this.form = {};
      this.dataSource = [];
      this.listSysUser();
      this.getSupplierAllList(1).then(() => {
        this.supplierOptions = this.supplierList;
      });
      this.getDicts('goods_price_type');
      this.getDetail(row);
      this.disabledCode = true;
    },
    view(row) {
      this.open = true;
      this.title = '编辑续费单';
      this.form = {};
      this.dataSource = [];
      this.listSysUser();
      this.getSupplierAllList(1).then(() => {
        this.supplierOptions = this.supplierList;
      });
      this.getDicts('goods_price_type');
      this.getDetail(row);
      this.disabled = true;
    },
    detailAfter() {
      this.dataSource = this.form.jzgPayOrderDetailVoList.map((v) => {
        return {
          ...v
        };
      });
    },
    // 获取续费单号
    addInit() {
      getPayOrderCode().then((res) => {
        this.form.payOrderCode = res.data || res.msg;
      });
    },
    cancel() {
      this.$tab.closeOpenPage({ name: 'PayOrder' });
      if (this.enterType == '1') {
        this.$router.push({ name: 'PayOrderDetail' });
      } else {
        this.$router.push({ name: 'PayOrder' });
      }
    },
    submitForm(close = true) {
      this.$refs.form.validate((valid) => {
        console.log('valid :>> ', valid);
        if (valid) {
          typeof this.classifyForm === 'function' && this.classifyForm();
          this.loading = true;
          if (this.form.id) {
            this.funcObj
              .update(this.form)
              .then((res) => {
                this.loading = false;
                if (res.code == 200) {
                  this.$modal.msgSuccess('操作成功');
                  if (close) {
                    // this.$tab.closeOpenPage({ path: '/dq/payOrder' });
                    this.$tab.closeOpenPage({ name: 'PayOrder' });
                  }
                  this.$emit('ok');
                } else {
                  this.$modal.msgError(res.msg);
                }
              })
              .catch((err) => {
                this.loading = false;
                console.log('err :>> ', err);
              });
          } else {
            this.funcObj
              .add(this.form)
              .then((res) => {
                this.loading = false;
                if (res.code == 200) {
                  this.$modal.msgSuccess('新增成功');
                  if (close) {
                    this.$tab.closeOpenPage({ name: 'PayOrder' });
                    // this.$router.push({ path: '/dq/payOrder' })
                  }
                  this.$emit('ok');
                } else {
                  this.$modal.msgError(res.msg);
                }
              })
              .catch((err) => {
                console.log('err :>> ', err);
                this.loading = false;
              });
          }
        }
      });
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
      this.multiple = val.length > 0;
    },
    selectHandle(row) {
      return 1;
    },
    handleAdd() {
      this.$refs.selectMaterialForm.show();
    },

    selectOk(data) {
      let selectArr = data.map((v) => {
        return {
          ...v,
          goodsId: v.id,
          surrogateStatus: v.supplyMode,
          shelfStatus: v.auditStatus,
          costPrice: v.costPrice,
          wholesalePrice: v.wholesalePrice,
          payTypeDictValue: v.goodsPriceTypeDictValue,
          beginDate: formatDate(new Date().getTime()),
          endDate: this.initEndDate(v.periodicNum)
        };
      });
      this.dataSource = this.dataSource.concat(selectArr);
      // 跟单阶段重复商品去重
      // let hash = {}
      // this.dataSource = this.dataSource.reduce((item, next) => {
      //   if (!hash[next.goodsId]) {
      //     hash[next.goodsId] = true
      //     item.push(next)
      //   }
      //   return item
      // }, [])
    },
    remoteMethod(query, listKey, key) {
      const optionKey = listKey + 'Options';
      if (query !== '') {
        this[optionKey] = this[listKey + 'List'].filter((item) => {
          return item[key].toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      } else {
        this[optionKey] = this[listKey + 'List'];
      }
    },
    quantityChange(row, index) {
      row.goodsAmount = row.goodsPrice * row.goodsNumber || '';
      row.payAmount = row.goodsPrice * row.goodsNumber || '';
      this.dataSource.splice(index, 1, row);
      if (row.payTypeDictValue == 4) {
        row.payAmount = row.goodsAmount;
      }
    },
    classifyForm() {
      console.log('this.dataSource :>> ', this.dataSource);
      this.form.jzgPayOrderDetailVoList = this.dataSource;
      // // 价格
      // this.form.averagePrice = this.dataSource.reduce((total, item) => {
      //   return total + +item.wholesalePrice
      // }, 0) / this.dataSource.length
      // // 金额
      // this.form.quotationPrice = this.dataSource.reduce((total, item) => {
      //   return total + +item.wholesalePrice
      // }, 0)
      console.log('this.form :>> ', this.form);
    },

    /**
     * @批量删除
     */
    handleBatchDelete() {
      if (this.selectedRows.length == 0) {
        this.$modal.msgError('请选择要删除的数据');
        return;
      }
      var ids = this.selectedRows.map((item) => item.goodsId).join(',');
      this.$modal
        .confirm('是否删除选中的数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          this.dataSource = this.dataSource.filter((item) => !ids.includes(item.goodsId));
        })
        .catch(() => {
          this.$modal.messageError({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    customerChange(value) {
      if (value) {
        getSupplier(value).then((res) => {
          if (res.data.supplierContactList.length > 0) {
            this.form.contacts = res.data.supplierContactList[0];
            this.form.operationManagerName = res.data.operationManagerName;
            this.contactsOptions = res.data.supplierContactList;
          } else {
            this.form.contacts = '';
            this.contactsOptions = [];
          }
        });
        this.getHistory(value);
      } else {
        this.historyDataSource = [];
      }
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        const keyArr = ['payAmount', 'goodsAmount', 'goodsNumber'];
        if (keyArr.includes(column.property)) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!Number.isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = '-';
        }
      });

      return sums;
    },
    DateDiff(Date_end, Date_start) {
      let aDate, oDate1, oDate2, iDays;
      Date_end = Date_end.split(' '); //将时间以空格划分为两个数组  第一个数组是 2019-05-20 第二个数组是 00：00：00
      aDate = Date_end[0].split('-'); //获取第一个数组的值
      oDate1 = new Date(aDate[0], aDate[1], aDate[2]); //将前半个数组以-拆分，每一个是一个数值
      Date_start = Date_start.split(' ');
      aDate = Date_start[0].split('-');
      oDate2 = new Date(aDate[0], aDate[1], aDate[2]);
      iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
      return iDays;
    },
    initEndDate(value) {
      let date = new Date();
      date = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ';
      date = Date.parse(new Date(date)) / 1000;
      date += 86400 * value;
      let newDate = new Date(parseInt(date) * 1000);
      return formatDate(newDate);
    },

    listSysUser() {
      listUser()
        .then((res) => {
          this.userList = res.rows;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getHistory(val) {
      let query = {
        supplierId: val
      };
      listPayOrderHistoryDetail(query).then((res) => {
        this.historyDataSource = res;
        console.log('history::>>', this.historyDataSource);
      });
    }
  }
};
</script>
 
<style lang="scss" scoped>
.box-card + .box-card {
  margin-top: 20px;
}

.top-line {
  display: flex;
  justify-content: space-between;
  padding-top: 20px;
}
</style>